package com.shujia.spark

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo13SparkPI {
  def main(args: Array[String]): Unit = {


    val conf: SparkConf = new SparkConf().setMaster("local[8]").setAppName("map")
    val sc: SparkContext = new SparkContext(conf)


    /**
      * 模拟打点
      *
      * 循环N次，每循环一次随机生成一个点
      * 判断点在圆内还是在圆外
      *
      */


    val list = 0 to 100000000

    val rdd1: RDD[Int] = sc.parallelize(list, 8)


    val pointRDD: RDD[(Double, Double)] = rdd1.map(i => {

      //随机生成x和y
      val x: Double = Random.nextDouble() * 2 - 1
      val y: Double = Random.nextDouble() * 2 - 1

      (x, y)
    })

    //取出圆内的点
    val yuanRDD: RDD[(Double, Double)] = pointRDD.filter(point => {
      val x: Double = point._1
      val y: Double = point._2

      x * x + y * y <= 1
    })


    val l: Long = yuanRDD.count()
    val sum: Int = list.length


    val pi = l / sum.toDouble * 4.0

    println(pi)

  }
}
